import uvicorn
import json
from fastapi import FastAPI, Header, Request, Depends,Response, status, File, UploadFile, HTTPException
from loguru import logger
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import pandas as pd
import io
from tempfile import SpooledTemporaryFile

app = FastAPI()
# 定义变量 trus
rectangle = True
appId="wxdc149e52c7e33f08"
appSecret="65841ef9b05663f64e8c0c59cec0c45e"

@logger.catch  # 异常记录装饰器、放到下面好像不行、应该是异步的关系。
def my_function(x, y, z):
    return [x, y, z]


# 添加首页
@app.on_event("startup")
async def startup_event():
    logger.add("logs/request.log", rotation="10 MB")

templates = Jinja2Templates(directory="templates")
@app.get("/", response_class=HTMLResponse)
async def upload(request: Request):
   return templates.TemplateResponse("index.html", {"request": request})


@app.post("/uploadfiles/")
async def uploadfiles(file1: UploadFile = File(...), file2: UploadFile = File(...)):
    try:
        output_path = "output_file.xls"
        # 将 SpooledTemporaryFile 转换为 BytesIO
        file_bytes1 = io.BytesIO(file1.file.read())
        file_bytes1.seek(0)
        df1 = pd.read_excel(file_bytes1, dtype={'牌号': str, '品名': str, '流转卡号': str, '管捆号': str},keep_default_na=False)
        print(df1.head())

        file_bytes2 = io.BytesIO(file2.file.read())
        file_bytes2.seek(0)
        df2 = pd.read_excel(file_bytes2, dtype={'牌号': str, '品名': str, '流转卡号': str, '管捆号': str},keep_default_na=False)
        print(df2.head())
        process_files(df1, df2, output_path)
        # 发送文件给用户
        # Read the Excel file as bytes
        excel_bytes = open(output_path, "rb").read()
        # Set response headers for Excel file
        response = Response(content=excel_bytes,
                            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        response.headers["Content-Disposition"] = f"attachment; filename={output_path}"
        return response
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"上传 Excel 文件时发生错误: {str(e)}")
def custom_match(a, b):
    a = str(a).replace('.0', '')
    b = str(b).replace('.0', '')
    if a == b:
        return True
    return False
def process_files(df_a, df_b, output_path):
    # df_a['合同号'] = df_a['合同号'].astype(str).str.rstrip('.0')
    # df_b['合同号'] = df_b['合同号'].astype(str).str.rstrip('.0')
    # merged_df = pd.merge(
    #     df_a,
    #     df_b,
    #     on=['合同号','试批号'],
    #     how='left',
    # )
    # print(df_a['合同号'])
    # print(df_b['合同号'])
    # print(merged_df['轧批号'])
    # # 将匹配成功的轧批号数据写入文件 A 的车批号列
    # df_a['车批号'] = merged_df['轧批号']
    # # 保存结果到输出文件
    # df_a.to_excel(output_path, index=False)
    # 使用自定义匹配函数
    # matched_df = merged_df[merged_df.apply(lambda row: custom_match(row['合同号_a'], row['合同号_b']), axis=1)]
    # print(matched_df)
    if df_a['日期'].dtype == 'datetime64[ns]':
        df_a['日期'] = df_a['日期'].dt.strftime('%Y-%m-%d')
    df_a['合同号'] = df_a['合同号'].astype(str)
    df_a['炉号'] = df_a['炉号'].astype(str)
    df_a['试批号'] = df_a['试批号'].astype(str)
    # for idx_a, row_a in df_a.iterrows():
    #     a_number_a = row_a['合同号']
    #     a_number_a = str(a_number_a).replace('.0', '')
    #     a_number_b = row_a['炉号']
    #     a_number_c = row_a['试批号']
    #     a_number_b=str(a_number_b).replace('.0', '')
    #     a_number_c=str(a_number_c).replace('.0', '')
    #     df_b['试批号'] = df_b['试批号'].astype(str)
    #     if a_number_c is not None and a_number_c != '' and a_number_c != ' ':
    #         filtered_data = df_b[(df_b['合同号'].astype(str).str.rstrip('.0') == a_number_a) &
    #                              (df_b['试批号'] == a_number_c)]
    #         first_match = filtered_data.iloc[0] if not filtered_data.empty else None
    #         if first_match is not None:
    #             # print("合同号：%，试批号：%",a_number_a,a_number_c,first_match['轧批号'])
    #             df_a.at[idx_a, '车批号'] = first_match['轧批号']
    #             if '牌号' in first_match.index:
    #                 df_a.at[idx_a, '牌号'] = first_match['牌号']
    #             if '品名' in first_match.index:
    #                 df_a.at[idx_a, '品名'] = first_match['品名']
    #             if '流转卡号' in first_match.index:
    #                 df_a.at[idx_a, '流转卡号'] = first_match['流转卡号']
    #             if '管捆号' in first_match.index:
    #                 df_a.at[idx_a, '管捆号'] = first_match['管捆号']
    #             if '外径' in first_match.index:
    #                 df_a.at[idx_a, '外径'] = first_match['外径']
    #             if '壁厚' in first_match.index:
    #                 df_a.at[idx_a, '壁厚'] = first_match['壁厚']
    #             if '长度' in first_match.index:
    #                 df_a.at[idx_a, '长度'] = first_match['长度']
    #         elif a_number_b is not None and a_number_b != '' and a_number_b != ' ':
    #             filtered_data = df_b[(df_b['合同号'].astype(str).str.rstrip('.0') == a_number_a) &
    #                                  (df_b['炉号'] == a_number_b)]
    #             first_match = filtered_data.iloc[0] if not filtered_data.empty else None
    #             if first_match is not None:
    #                 # print("合同号：%，炉号：%", a_number_a, a_number_b, first_match['轧批号'])
    #                 df_a.at[idx_a, '车批号'] = first_match['轧批号']
    #                 if '牌号' in first_match.index:
    #                     df_a.at[idx_a, '牌号'] = first_match['牌号']
    #                 if '品名' in first_match.index:
    #                     df_a.at[idx_a, '品名'] = first_match['品名']
    #                 if '流转卡号' in first_match.index:
    #                     df_a.at[idx_a, '流转卡号'] = first_match['流转卡号']
    #                 if '管捆号' in first_match.index:
    #                     df_a.at[idx_a, '管捆号'] = first_match['管捆号']
    #                 if '外径' in first_match.index:
    #                     df_a.at[idx_a, '外径'] = first_match['外径']
    #                 if '壁厚' in first_match.index:
    #                     df_a.at[idx_a, '壁厚'] = first_match['壁厚']
    #                 if '长度' in first_match.index:
    #                     df_a.at[idx_a, '长度'] = first_match['长度']
    #     elif a_number_b is not None and a_number_b != '' and a_number_b != ' ':
    #         filtered_data = df_b[(df_b['合同号'].astype(str).str.rstrip('.0') == a_number_a) &
    #                              (df_b['炉号'] == a_number_b)]
    #         first_match = filtered_data.iloc[0] if not filtered_data.empty else None
    #         if first_match is not None:
    #             # print("合同号：%，炉号：%", a_number_a, a_number_b, first_match['轧批号'])
    #             df_a.at[idx_a, '车批号'] = first_match['轧批号']
    #             if '牌号' in first_match.index:
    #                 df_a.at[idx_a, '牌号'] = first_match['牌号']
    #             if '品名' in first_match.index:
    #                 df_a.at[idx_a, '品名'] = first_match['品名']
    #             if '流转卡号' in first_match.index:
    #                 df_a.at[idx_a, '流转卡号'] = first_match['流转卡号']
    #             if '管捆号' in first_match.index:
    #                 df_a.at[idx_a, '管捆号'] = first_match['管捆号']
    #             if '外径' in first_match.index:
    #                 df_a.at[idx_a, '外径'] = first_match['外径']
    #             if '壁厚' in first_match.index:
    #                 df_a.at[idx_a, '壁厚'] = first_match['壁厚']
    #             if '长度' in first_match.index:
    #                 df_a.at[idx_a, '长度'] = first_match['长度']
    #         elif a_number_c is not None and a_number_c != '' and a_number_c != ' ':
    #             filtered_data = df_b[(df_b['合同号'].astype(str).str.rstrip('.0') == a_number_a) &
    #                                  (df_b['试批号'] == a_number_c)]
    #             first_match = filtered_data.iloc[0] if not filtered_data.empty else None
    #             if first_match is not None:
    #                 # print("合同号：%，试批号：%", a_number_a, a_number_c, first_match['轧批号'])
    #                 df_a.at[idx_a, '车批号'] = first_match['轧批号']
    #                 if '牌号' in first_match.index:
    #                     df_a.at[idx_a, '牌号'] = first_match['牌号']
    #                 if '品名' in first_match.index:
    #                     df_a.at[idx_a, '品名'] = first_match['品名']
    #                 if '流转卡号' in first_match.index:
    #                     df_a.at[idx_a, '流转卡号'] = first_match['流转卡号']
    #                 if '管捆号' in first_match.index:
    #                     df_a.at[idx_a, '管捆号'] = first_match['管捆号']
    #                 if '外径' in first_match.index:
    #                     df_a.at[idx_a, '外径'] = first_match['外径']
    #                 if '壁厚' in first_match.index:
    #                     df_a.at[idx_a, '壁厚'] = first_match['壁厚']
    #                 if '长度' in first_match.index:
    #                     df_a.at[idx_a, '长度'] = first_match['长度']
    # for idx_a, row_a in df_b.iterrows():
    #    print("B-", row_a['合同号'], row_a['炉号'], row_a['试批号'])
    #
    # #未适配合同号：%，试批号：% 1123090236050 924011112
    # filtered_data = df_b[(df_b['合同号'].astype(str).str.rstrip('.0') == '1123090236050') & (df_b['炉号'] == '924011112')]
    # first_match = filtered_data.iloc[0] if not filtered_data.empty else None
    # print(filtered_data)
    # if first_match is None:
    #     print('使用试批号')
    #     # print("未适配合同号：%，试批号：%", a_number_a, a_number_b)
    #     filtered_data = df_b[(df_b['合同号'].astype(str).str.rstrip('.0') == '1123090236050') & (df_b['试批号'] == '924011112')]
    #     print(filtered_data)
    # else:
    #     print('匹配成功')
    # 外部条件检查
    for idx_a, row_a in df_a.iterrows():
        a_number_a = row_a['合同号']
        a_number_b = row_a['炉号']
        a_number_c = row_a['试批号']
        a_number_a = str(a_number_a).replace('.0', '')
        a_number_b = str(a_number_b).replace('.0', '')
        a_number_c = str(a_number_c).replace('.0', '')

        if a_number_c and a_number_c != ' ':
            filtered_data = df_b[(df_b['合同号'] == a_number_a) & (df_b['试批号'] == a_number_c)]
            first_match = filtered_data.iloc[0] if not filtered_data.empty else None
            if first_match is None:
                filtered_data = df_b[(df_b['合同号'] == a_number_a) & (df_b['炉号'] == a_number_c)]
                first_match = filtered_data.iloc[0] if not filtered_data.empty else None
                if first_match is not None:
                    df_a.at[idx_a, '车批号'] = first_match['轧批号']
                    for col in ['炉号', '试批号', '牌号', '品名', '流转卡号', '管捆号', '外径', '壁厚', '长度']:
                        if col in first_match.index:
                            df_a.at[idx_a, col] = first_match[col]
            else:
                df_a.at[idx_a, '车批号'] = first_match['轧批号']
                for col in ['炉号', '试批号', '牌号', '品名', '流转卡号', '管捆号', '外径', '壁厚', '长度']:
                    if col in first_match.index:
                        df_a.at[idx_a, col] = first_match[col]
        if a_number_b and a_number_b != ' ':
            filtered_data = df_b[(df_b['合同号'] == a_number_a) & (df_b['炉号'] == a_number_b)]
            first_match = filtered_data.iloc[0] if not filtered_data.empty else None
            if first_match is None:
                # print("未适配合同号：%，试批号：%", a_number_a, a_number_b)
                filtered_data = df_b[(df_b['合同号'] == a_number_a) & (df_b['试批号'] == a_number_b)]
                first_match = filtered_data.iloc[0] if not filtered_data.empty else None
                if first_match is not None:
                    df_a.at[idx_a, '车批号'] = first_match['轧批号']
                    for col in ['炉号', '试批号', '牌号', '品名', '流转卡号', '管捆号', '外径', '壁厚', '长度']:
                        if col in first_match.index:
                            df_a.at[idx_a, col] = first_match[col]
            else:
                df_a.at[idx_a, '车批号'] = first_match['轧批号']
                for col in ['炉号', '试批号', '牌号', '品名', '流转卡号', '管捆号', '外径', '壁厚', '长度']:
                    if col in first_match.index:
                        df_a.at[idx_a, col] = first_match[col]

    # 保存结果到输出文件
    # 创建一个 ExcelWriter 对象，指定引擎为 xlwt （如果需要支持 .xls 格式）
    df_a.to_excel(output_path, index=False)
    # 保存 DataFrame 到 Excel 文件，保留原始格式


    # df_a.to_excel(output_path, index=False)


@app.post("/showmessage/")
async def showmessage():
    return {"message": "这是一个消息框！"}

# 定义依赖项，用于检查请求头中是否包含 openId
def check_open_id(openId: str = Header(None)):
    logger.info(openId)
    returnvar = json.loads('{}')
    returnvar['statusCode'] = 401
    returnvar['meg'] = "Missing openId in the request header"
    if not openId:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=json.dumps(returnvar),
        )
    if openId is None or openId == "":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=json.dumps(returnvar),
        )
    return openId

async def send_http_post(data):
    try:
        logger.info(data)
    except Exception as e:
        logger.info('fail with unknown error: {}'.format(e))


if __name__ == '__main__':
    uvicorn.run(app, host='0.0.0.0', port=12306)
    # file_a_path = "output_file.xlsx"
    # file_b_path = "33.xls"
    # output_path = "output_file.xls"
    # df1 = pd.read_excel(file_a_path, dtype={'牌号':str,'品名': str,'流转卡号':str,'管捆号':str},keep_default_na=False)
    # df2 = pd.read_excel(file_b_path, dtype={'牌号':str,'品名': str,'流转卡号':str,'管捆号':str},keep_default_na=False)
    # process_files(df1, df2, output_path)
